package com.espirit.finance.core;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.GenericService;

@Service
public class AcctTermService {
	@Resource
	GenericService genericService;
	
	public AcctTerm getMaxAcctTerm(){
		String ql = "  from " + AcctTerm.class.getName() + " a order by a.name desc ";
		AcctTerm acctTerm = (AcctTerm) genericService.searchByQl(new QLInfo(ql, true)).getData(0);
		return acctTerm;
	}
	
	public AcctTerm generate(){
		Calendar begin = Calendar.getInstance();
		begin.clear();
		begin.setTime(new Date());
		return generate(begin.get(Calendar.YEAR), begin.get(Calendar.MONTH) + 1);
	}
	
	public AcctTerm generate(int year, int month){
		AcctTerm acctTerm = new AcctTerm();
		
		Calendar begin = Calendar.getInstance();
		begin.clear();
		begin.set(year, month -1, 1, 0, 0, 0);
		int lastDay = begin.getActualMaximum(Calendar.DAY_OF_MONTH);
		
		Calendar end = Calendar.getInstance();
		end.clear();
		end.set(year, month - 1, lastDay, 23, 59, 59);
		
		acctTerm.setBeginDate(begin.getTime());
		acctTerm.setEndDate(end.getTime());
		
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM"); 
		String name = df.format(begin.getTime());
		acctTerm.setName(name);
		
		AcctTerm example = new AcctTerm();
		example.setName(name);
		example = genericService.searchAll(example).getData(0);
		
		if (example == null){
			acctTerm = genericService.add(acctTerm);
		} else {
			acctTerm = example;
		}
		
		return acctTerm;
	}
	
	public AcctTerm generateNext(AcctTerm acctTerm){
		int year = acctTerm.getYear() ;
		int month = acctTerm.getMonth();
		if (month == 12){
			month = 1;
			year ++;
		} else {
			month ++;
		}
		return generate(year, month);
	}
	
	public AcctTerm getLastAcctTerm(AcctTerm acctTerm){
		if (acctTerm == null) return null;
		acctTerm = genericService.load(AcctTerm.class, acctTerm.getId());
		int year = acctTerm.getYear() ;
		int month = acctTerm.getMonth();
		if (month == 1){
			month = 12;
			year --;
		} else {
			month --;
		}
		String name = String.format("%04d", year) + "-" + String.format("%02d", month);
		AcctTerm example = new AcctTerm();
		example.setName(name);
		return genericService.searchAll(example).getData(0);
	}
}
